package com.xqboss.apps.service.order.pay.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xqboss.apps.constant.YeepayConfig;
import com.xqboss.apps.domain.order.PayApply;
import com.xqboss.apps.dto.order.SignPayDto;
import com.xqboss.apps.dto.order.TradeResultDto;
import com.xqboss.apps.enums.order.OrderTypeEnum;
import com.xqboss.apps.enums.user.PayTypeEnum;
import com.xqboss.apps.service.order.pay.PayExecutor;
import com.xqboss.apps.service.user.YeepayWalletService;
import com.xqboss.common.exception.ServiceException;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.common.request.YopRequest;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component(value = PayTypeEnum.Code.YeePay_JH)
public class YeePayJHExecutor extends BaseYeePay {

    @Override
    public SignPayDto signPay(PayApply info) {
        YopRequest request = new YopRequest("/rest/v1.0/cashier/unified/order", "POST");
        request.addParameter("parentMerchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("merchantNo", yeepayConfig.getMerchantNo());
        request.addParameter("orderId", info.getId());
        request.addParameter("orderAmount", info.getOrderAmount().toPlainString());
        request.addParameter("goodsName", "加油蛙-" + info.getSubject());
        if (info.getOrderType() != null && (info.getOrderType() == OrderTypeEnum.Market || info.getOrderType() == OrderTypeEnum.Gift)) {
            request.addParameter("fundProcessType", "DELAY_SETTLE");
        } else {
            request.addParameter("fundProcessType", "REAL_TIME");
        }
        request.addParameter("notifyUrl", yeepayConfig.getPayNotifyUrl());
        request.addParameter("expiredTime", info.getExpireTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        request.addParameter("returnUrl", yeepayConfig.getPayReturnUrl());
        // 无卡参数配置
        Map<String, String> noCardParam = new HashMap<>();
        noCardParam.put("userType", "USER_ID");
        noCardParam.put("userNo", yeepayConfig.getUserPrefix() + info.getUserId());
        request.addParameter("noCardParam", JSON.toJSONString(noCardParam));
        // 清算成功的回调
//        request.addParameter("csNotifyUrl", "");
        /*
        按易宝风控部门要求，请在businessInfo参数里，上传一个json字符串，以提高准确性降低误伤的概率，内容如下：
        藏品系列：collectionSeries（String）
        藏品名称：collectionName（String）
        藏品编号：collectionId（String），注意此参数必须藏品维度唯一、稳定，与藏品永久绑定，用于跟踪藏品流转情况
        交易市场类型：marketType（String），枚举：首发（一级市场）、转卖（二级市场）、转赠，传中文枚举即可
        注册手机号：userRegisterMobile（String）
        注册时间：registTime（date）
        注册IP：registIp（String），如果获取不到，可以传""
        注册证件号：userRegisterIdNo（String）
        注册用户ID（商户端唯一标识）：registId（String）
        */
        Map<String, String> businessInfo = new HashMap<>();
        businessInfo.put("collectionSeries", "");
        businessInfo.put("collectionName", "");
        businessInfo.put("collectionId", "");
        businessInfo.put("marketType", "首发");
        businessInfo.put("userRegisterMobile", "");
        businessInfo.put("registTime", "");
        businessInfo.put("registIp", "");
        businessInfo.put("userRegisterIdNo", "");
        businessInfo.put("registId", "");

        request.addParameter("businessInfo", JSON.toJSONString(businessInfo));
//        request.addParameter("payerInfo", JSON.toJSONString(payerInfo));
        request.addParameter("limitPayType", "YJZF");

        try {
            YopResponse response = yeepayConfig.getClient().request(request);
            Map<String, String> ret = (Map<String, String>) response.getResult();
            if("00000".equals(ret.get("code"))){
                SignPayDto dto = new SignPayDto();
                //易宝收款订单号
                dto.setOutTradeNo(ret.get("uniqueOrderNo"));
    //            //收银台链接
                dto.setPayInfo(ret.get("cashierUrl"));
                return dto;
            }
            log.error("生成支付失败:request:{} - ret:{}", JSON.toJSONString(request), response.getStringResult());
            throw new ServiceException("支付失败，请重试");
        } catch (YopClientException e) {
            log.error("生成支付异常", e);
            throw new ServiceException("支付失败，请重试");
        }
    }
}
